const connectionObj = {


};
const buildProxy = function(connection) {
    return new Proxy({}, {
        get(target, key) {
            if (key == '$this') {
                return connection;
            }
            return function() {
                connection.invoke(key, ...arguments)
            }
        }
    })
}
var lockResolver;
if (navigator && navigator.locks && navigator.locks.request) {
    const promise = new Promise((res) => {
        lockResolver = res;
    });

    navigator.locks.request('unique_lock_name', { mode: "shared" }, () => {
        return promise;
    });
}

export default function start(url, options, onConnection, onError) {
    if (connectionObj[url]) {
        return connectionObj[url];
    }
    const connection = new signalR.HubConnectionBuilder()
        .withUrl(url, {
            accessTokenFactory: () => Token.value()
        })
        .withAutomaticReconnect()
        .configureLogging(signalR.LogLevel.Information)
        .build();
    connection.onreconnected(onConnection || (() => console.log('连接成功')));
    connection.start()
        .then((onConnection || (() => console.log('连接成功'))))
        .catch(onError || (() => console.error('连接失败')));

    connection.onclose(() => {
        console.log('连接断开');
    });
    for (const key in options) {
        if (Object.hasOwnProperty.call(options, key)) {
            const element = options[key];
            if (typeof element === 'function') {
                connection.on(key, element);
            }
        }
    }
    connectionObj[url] = buildProxy(connection);
    return connectionObj[url];
}